﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using DevExpress.Web.Mvc;
using System.Data;
using System.IO;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
   /// <summary>
    /// 文件阅办处理
   /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class TaskManagerController : AdminBaseController
    {
        /// <summary>
        /// 文件阅办处理
        /// </summary>
        /// <returns>返回文件阅办处理主页面视图</returns>
        [AuthorityActionFilter("m_TaskManager", Order = 1)]
        [LogPageActionFilter("文件阅办处理", Order = 2)]
        public ActionResult Index()
        {
            string emplNo=OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            string entityNo=GlobalConstant.ENTITYNO;
            BLL.HREmplPosition hrEmplPositionBLL = new BLL.HREmplPosition();
            DataSet ds = hrEmplPositionBLL.GetEmplPositionInfo(emplNo, entityNo);
            string deptNos = "";
            string strwhere = " (FStatus='1') ";
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                deptNos += "'" + dr["FDeptNo"] + "',";
            }
            if (deptNos != "")
            {
                deptNos = deptNos.Substring(0, deptNos.LastIndexOf(","));
                strwhere += "   and  FDeptNo IN (" + deptNos + ")";
            }
           
            List<Model.Task> TaskList = GetTaskListList(strwhere, 1);
            return View(TaskList);
        }

        [AuthorityActionFilter("m_TaskManager", Order = 1)]
        public ActionResult TaskEdit(string taskID)
        {
            BLL.Task taskBLL = new BLL.Task();
            Model.Task taskModel = new Model.Task();
            if (taskID != null)
            {
                taskModel = taskBLL.GetModel(decimal.Parse(taskID));
            }
            BLL.TaskDo taskDoBLL = new BLL.TaskDo();
            List<Model.TaskDo> taskDoList = taskDoBLL.GetModelList("FTaskID=" + taskID + "");

            ViewData["TaskDoList"] = taskDoList;

            BLL.TaskAttach TaskAttachBLL = new BLL.TaskAttach();
            ViewData["TaskAttachList"] = TaskAttachBLL.GetModelList(" FTaskDoID in (select FTaskDoID from dbo.t_TaskDo where FTaskID=" + taskID + " ) ");

            return View(taskModel);
        }

        public ActionResult Save()
        {

            BLL.Task TaskBLL = new BLL.Task();
            Model.Task TaskModel = TaskBLL.GetModel(decimal.Parse(Fetch.Post("hdFTaskID")));
            try
            {
                //获取文件类型、大小、名称
                Model.TaskAttach docAttachModel = new Model.TaskAttach();
                string status = Fetch.Post("FStatus");
                if (status == "1")
                {
                    if (Request.Files.Count > 0)
                    {
                        HttpPostedFileBase fu = Request.Files[0];
                        string type = fu.ContentType;
                        int size = fu.ContentLength;
                        if (size > 0)
                        {
                            string factFileName = Path.GetFileNameWithoutExtension(fu.FileName);

                            //获取文件的扩展名
                            string extension = Path.GetExtension(fu.FileName).ToLower();
                            string url = "/ElingOA6_Admin_DSJCJ/" + "Publish/Task/" + DateTime.Now.Year + "/" + DateTime.Now.Month.ToString().PadLeft(2, '0');
                            if (size < 100 * 1024 * 1024)
                            {
                                //改变附件名称
                                string strnewFileNmae = GenerateUtil.GenerateStringId();
                                //判断附件保存文件夹是否存在
                                GenerateUtil.Addfolder(url);
                                string fullpath = System.Web.HttpContext.Current.Server.MapPath(url) + "\\" + strnewFileNmae + extension;

                                //判断是否存在相同的文件
                                if (System.IO.File.Exists(fullpath) == false)
                                {
                                    //上传文件到硬盘
                                    fu.SaveAs(fullpath);
                                    docAttachModel.FEntityNo = Common.GlobalConstant.ENTITYNO;
                                    docAttachModel.FAttachSvrFileName = url + "/" + strnewFileNmae + extension;
                                    docAttachModel.FAttachOldFileName = factFileName + extension;
                                    //获取文件二进制格式
                                    System.IO.Stream stream = fu.InputStream;
                                    byte[] buffer = new byte[stream.Length];
                                    stream.Read(buffer, 0, (int)stream.Length);
                                    stream.Close();
                                    //docAttachModel.FAttachContent = buffer;
                                    docAttachModel.FAttachFileExt = type;

                                }
                            }
                        }
                        else
                        {
                            docAttachModel = null;
                        }
                    }
                    else
                    {
                        docAttachModel = null;
                    }
                }

                Model.TaskDo TaskDoModel = new Model.TaskDo();
                TaskDoModel.FInsDate = DateTime.Now;
                TaskDoModel.FInsIP = Common.GenerateUtil.GetClientIPv4Address();
                TaskDoModel.FNote = Fetch.Post("FNote");
                TaskDoModel.FEmplNo = OperateSession.get(Common.GlobalConstant.PARAM_FEMPLNO);
                TaskDoModel.FEntityNo = Common.GlobalConstant.ENTITYNO;
                TaskDoModel.FTaskID = decimal.Parse(Fetch.Post("hdFTaskID"));
                if (status == "0")
                {
                    TaskDoModel.FStatus = "1";
                    docAttachModel = null;
                }
                else if (status == "1")
                {
                    if (TaskModel.FEndDate < DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd")))
                    {
                        TaskDoModel.FStatus = "3";
                    }
                    else
                    {
                        TaskDoModel.FStatus = "2";
                    }
                    TaskModel.FStatus = "2";
                }
                else
                {
                    TaskDoModel.FStatus = "4";
                    docAttachModel = null;
                    TaskModel.FStatus = "4";
                }

                BLL.TaskDo TaskDoBLL = new BLL.TaskDo();
                if (status == "1" || status == "2")
                {
                    TaskDoBLL.Add(TaskDoModel, docAttachModel, TaskModel);
                }
                else
                {
                    TaskDoBLL.Add(TaskDoModel, docAttachModel, null);
                }
                ViewData["jsAlert"] = "OK";
            }
            catch
            {
                ViewData["jsAlert"] = "error";
            }
            BLL.TaskDo taskDoBLL = new BLL.TaskDo();
            List<Model.TaskDo> taskDoList = taskDoBLL.GetModelList("FTaskID=" + Fetch.Post("hdFTaskID") + "");

            ViewData["TaskDoList"] = taskDoList;
            BLL.TaskAttach TaskAttachBLL = new BLL.TaskAttach();
            ViewData["TaskAttachList"] = TaskAttachBLL.GetModelList(" FTaskDoID in (select FTaskDoID from dbo.t_TaskDo where FTaskID=" + Fetch.Post("hdFTaskID") + " ) ");
            return View("TaskEdit", TaskModel);
        }

        public ActionResult TaskManagerPartial()
        {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());
            string callbackArg = DevExpressHelper.CallbackArgument;
            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();
            string type = Request.Params["Type"];
            string gNO = Request.Params["gNO"];
            string dutyNo = Request.Params["DutyNo"];

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1;
            }
            string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            string entityNo = GlobalConstant.ENTITYNO;
            BLL.HREmplPosition hrEmplPositionBLL = new BLL.HREmplPosition();
            DataSet ds = hrEmplPositionBLL.GetEmplPositionInfo(emplNo, entityNo);
            string deptNos = "";
            string strwhere = " (FStatus='1') ";
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                deptNos += "'" + dr["FDeptNo"] + "',";
            }
            if (deptNos != "")
            {
                deptNos = deptNos.Substring(0, deptNos.LastIndexOf(","));
                strwhere += "   and  FDeptNo IN (" + deptNos + ")";
            }
            List<Model.Task> TaskList = GetTaskListList(strwhere, pageIndex);
            return PartialView("TaskManagerPartial", TaskList);
        }

        /// <summary>
        /// 获取定义的工作时间数据
        /// </summary>
        /// <param name="strWhere">查询条件</param>
        /// <param name="pageIndex">第几页</param>
        /// <returns>查询出来的数据</returns>
        private List<Model.Task> GetTaskListList(string strWhere, int pageIndex)
        {
            BLL.Common commonBll = new BLL.Common();
            BLL.Task TaskBLL = new BLL.Task();
            string fiedls = "*";
            int total;
            DataSet ds = commonBll.GetListByPage("dbo.fn_getTask('" + Common.GlobalConstant.PARAM_DEPTNO + "')", fiedls, Common.GlobalConstant.CONSTRING_PAGESIZE, pageIndex, strWhere, "FEndDate", 1, out total);
            List<ElingOA6_Admin_DSJCJ.Model.Task> taskList = TaskBLL.DataTableToList(ds.Tables[0]);
            List<Model.Task> taskAllList = new List<Model.Task>();

            int pageRowSize = Common.GlobalConstant.CONSTRING_PAGESIZE;
            for (int i = 0; i < total; i++)
            {
                taskAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (taskList.Count > i)
                {
                    taskAllList[((pageIndex - 1) * pageRowSize) + i] = taskList[i];
                }
            }
             
            return taskAllList;
        }
    }
}
